import os, sys, glob

with open('TabOfContent.ipynb') as f:
    construct = f.readlines()

# a cell with markdown type in ipynb file
cell = construct[2:9]
# Storing cells will be inderted to ipynb file
inert_cells = []
for i, e in enumerate(os.listdir(os.path.curdir)):
    if e in ['Materials', '.ipynb_checkpoints']: continue
    if os.path.isdir(e) and not e.startswith('.'):
        os.chdir(e)
        # A directory is the first levle
        cell[4] =  f"    \"# [<font color=blue size=5>{e}</font>]({e})\"\n"
        inert_cells.extend(cell)
        try:
            files = glob.glob('*.ipynb', recursive=False)
            PYTHON = e + '.ipynb'
            if PYTHON in files:
                files.remove(PYTHON)
                files.insert(0, PYTHON)
            for file in files:
                filen_name = os.path.splitext(file)[0]
                # An ipynb file in the directory is the second levle
                # Note that file path seperator in System
                cell[4] =  f"    \"## [<font size=3 color=black>{filen_name}</font>]({e + '/' + file})\"\n"
                inert_cells.extend(cell)
        except Exception as err:
            print('err', g=g)
        finally:
            os.chdir(os.path.pardir)
        # break

# Merge cells in ipynb and inserted to overall list
head = construct[:2]
head.extend(inert_cells)
tail = construct[9:]
overall = head + tail

# Set the ipynb file name of TOC with this directory name
with open(os.path.basename(os.getcwd()) + '.ipynb', 'w', encoding='utf8') as f:
    for line in overall:
        f.write(line)